package org.buptsse.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.Base64Helper;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.StreamTool;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class RegisterTwoActivity extends Activity {

	private Handler handler=new Handler()
	{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case APPConstant.UploadPhotoError:
				Toast.makeText(getApplicationContext(), "上传失败", 1000).show();
				break;

			case APPConstant.UploadPhotoFinish:
				//Toast.makeText(getApplicationContext(), "finish", 1000).show();
				Intent intent=new Intent();
				intent.setClass(RegisterTwoActivity.this, MainCenterActivity.class);
				startActivity(intent);
				finish();
				break;
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	private ImageView image,addImageButton;
	private Button finishButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 去掉任务条
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.lregister_two);

		image=(ImageView) findViewById(R.id.image);
		addImageButton=(ImageView) findViewById(R.id.add_image_button);
		addImageButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//选择图片
			}
		});
		finishButton=(Button) findViewById(R.id.finish_button);
		finishButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				uplodadPhoto();
			}
		});
	}
	
	private void uplodadPhoto()
	{
		image.buildDrawingCache();
		//Bitmap bmap = image.getDrawingCache();
		Bitmap bitmap=image.getDrawingCache();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
		byte[] data=os.toByteArray();
		//进行base64转码
		String data_str=Base64Helper.encode(data, 0, data.length);
		UploadPhotoThread ut=new UploadPhotoThread(data_str, this);
		ut.start();
	}
	
	private class UploadPhotoThread extends Thread
	{
		String photo_str;
		Context context;
		public UploadPhotoThread(String image_str,Context context)
		{
			photo_str=image_str;
			this.context=context;
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(this.context, handler)==false)
			{
				return;
			}
			HttpPost post=new HttpPost(APPConstant.uploadPhotoUrl);
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("name", GloableInstance.user.getName()));
			param.add(new BasicNameValuePair("password", GloableInstance.user.getPassword()));
			param.add(new BasicNameValuePair("photo", photo_str));
			try {
				post.setEntity(new UrlEncodedFormEntity(param,"UTF-8"));
				HttpResponse response=new DefaultHttpClient().execute(post);
				HttpEntity entity=response.getEntity();
				InputStream content=entity.getContent();
				String result=StreamTool.convertStreamToString(content);
				System.out.println("upload photo result:"+result);
				if(!result.equals("success"))
				{
					Message msg=handler.obtainMessage(APPConstant.UploadPhotoFinish);
					handler.sendMessage(msg);
					return;
				}else {
					Message msg=handler.obtainMessage(APPConstant.UploadPhotoError);
					handler.sendMessage(msg);
					return;
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}